package dal
import (
	"fmt"
	"reflect"
	"alisms/model"
	"log"
	"time"
	"github.com/BurntSushi/toml"
	"github.com/yunhor/alisms"
)

type msg struct {
}
func (m msg) Sendmsg(rs []model.SmsN ,signName string ,templateCode string ,maps []string ,tstr string)(srt model.SendRT) {
	sendtest:=false
	var smscfg alisms.UserParams
	if _, err := toml.DecodeFile("conf/sms.toml", &smscfg); err != nil {
		log.Fatal(err)
	}
	smscfg.TemplateCode = templateCode
	smscfg.SignName = signName
	srt = tosendsms(rs, &smscfg, maps, tstr, sendtest)
	fmt.Println(srt)
	return
}
func genstr(rec model.SmsN, maps []string, tstr string) (rt string) {
	l := len(maps)

	str := fmt.Sprintf("\"time\":\"%s\"", tstr)
	if l > 0 {
		for i := 0; i < len(maps); i++ {
			tmp := ""
			t := reflect.TypeOf(rec)
			v := reflect.ValueOf(&rec).Elem()
			for k := 0; k < v.NumField(); k++ {
				if t.Field(k).Name == fmt.Sprintf("Col%d", i) {
					field := v.Field(k)
					tmp = field.String()
				}
			}
			// if i > 0 {
			// 	str += ","
			// }
			str += fmt.Sprintf(",\"%s\":\"%s\"", maps[i], tmp)
		}
		rt = "{" + str + "}"
	}
	fmt.Println("params:%s", rt)
	return
}
func tosendsms(rs []model.SmsN, smscfg *alisms.UserParams, maps []string, tstr string, sendtest bool) (srt model.SendRT) {

	if sendtest {
		smscfg.TemplateParam = genstr(rs[0], maps, tstr)
		rt, str, err := alisms.SendMessage(smscfg)
		fmt.Println(rt)
		fmt.Println(str)
		if err != nil {
			fmt.Println(err.Error())
		}
	} else {
		Sc := 0
		Fc := 0
		fs := srt.FS
		flist:=srt.Flist
		for _, tmp := range rs {
			// wxb
			smscfg.TemplateParam = genstr(tmp, maps, tstr)
			smscfg.PhoneNumbers = tmp.Phone
			rt, str, _ := alisms.SendMessage(smscfg)
			fmt.Println(rt)
			fmt.Println(str)
			if rt {
				Sc++
			} else {
				Fc++
				errstr := fmt.Sprintf("编号：%s,错误：%s\n", tmp.BM, str)
				fmt.Println(errstr)
				fs = append(fs, errstr)
                flist =append(flist,tmp)
			}
			time.Sleep(time.Millisecond * 50)
		}
		srt.TC = len(rs)
		srt.FC = Fc
		srt.SC = Sc
		srt.FS = fs
		srt.Flist = flist
		// todo 收集发送失败的数据,返回给前端 失败列表
		fmt.Printf("\n成功：%d,失败：%d", Sc, Fc)
	}
	return
}